home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2019 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  65 lines

  1. Path: thor.tu.hac.com!collins
  2. From: collins@thor.tu.hac.com (Ron Collins)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: union ?
  5. Date: 18 Jan 1996 14:10:47 GMT
  6. Organization: Advanced Depot Systems
  7. Message-ID: <4dlkd7$qj3@hacgate2.hac.com>
  8. References: <4dkigi$c29@linet02.li.net>
  9. NNTP-Posting-Host: thor.tu.hac.com
  10.  
  11. Don Matthews (don@newshost.li.net) wrote:
  12. : A union consist of many different variables.
  13. : But at any one time it can only hold one of those variables.
  14. : Is that correct?
  15.  
  16. More or less ... a union, in its simplest form, consists of many different
  17. variables, *all occupying the same storage locations*.  For example:
  18.  
  19. union FOO {
  20.    char   var1;
  21.    int    var2;
  22.    float  var3;
  23. };
  24.  
  25. union FOO   bar;    /* make a variable of the union itself */
  26.  
  27. I can now assign to any of bar.var1, bar.var2, or bar.var3.  A value will
  28. immediately appear in the other 2 variables.  What that value _means_ is
  29. completely implementation-dependant.
  30.  
  31. A real-life example (kind of):  On an IBM-PC, I want to pack two characters
  32. (8 bits each) into a single 16-bit integer:
  33.  
  34. union CPACK_U {
  35.    char   cval[2];    /* a total of 16 bits here */
  36.    int    ival;        /* 16 bits here, too */
  37. };
  38.  
  39. union CPACK_U  cpack;
  40.  
  41. cpack.cval[0] = 'A';
  42. cpack.cval[1] = 'B';
  43. printf("ival=%4.4x",cpack.ival);
  44.  
  45. will print "ival=4241" ('A' is hex 41,  'B' is hex 42).
  46.  
  47. Note that using silly tricks like this make your code completely non-
  48. portable, and can lead to some of the most frustrating debugging sessions
  49. of your career.  Of course, silly tricks like this are sometimes the
  50. best way (fastest, cheapest) to get a job done.
  51.  
  52.  
  53.                         -- Collins --
  54.                         
  55. -----
  56. The views expressed here are mine alone.
  57.  
  58. Ron Collins/Hughes Aircraft Company/M20,P20/Tucson Az 85706
  59. rcollins@thor.tu.hac.com    collins@seagull.rtd.com
  60. ยก----
  61.  
  62.  
  63.  
  64.  
  65.